package com.diploma.project.aiqiyi.aspect;

import com.diploma.project.aiqiyi.common.annotation.AuthControl;
import com.diploma.project.aiqiyi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Order(5)
@Component
public class AuthAspect {

    @Autowired
    private UserService userService;

    @Pointcut("execution(public * com.diploma.project.aiqiyi..controller..*.*(..))")
    public void auth() {

    }

    @Around("auth()")
    public Object processHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Object target = joinPoint.getTarget();
            AuthControl authControl = target.getClass().getAnnotation(AuthControl.class);

            Method currentMethod = target.getClass().getMethod(methodSignature.getName(),
                    methodSignature.getParameterTypes());
            AuthControl methodAuthCtrl = currentMethod.getAnnotation(AuthControl.class);

            if (methodAuthCtrl != null) {
                authControl = methodAuthCtrl;
            }
            if (authControl != null && authControl.checkLogin()) {
                userService.checkUser();
            }
            return joinPoint.proceed();
        } catch (Exception e) {
            throw e;
        } catch (Throwable throwable) {
            return joinPoint.proceed();
        }
    }
}
